﻿using System;
using System.Data;
using System.Data.OleDb;

namespace ZhiAo.BaseFramework.DBConnection
{
    internal class OleDB : I_DB
    {
        //数据库连接字符串
        private string connectionString;
        //数据库连接类型
        private ConnectionType connType;
        //错误信息
        private string errorMessage = "";

        //构造函数
        public OleDB(string Connection, ConnectionType ConnType)
        {
            this.connectionString = Connection;
            this.connType = ConnType;
        }

        private void AttachParameters(OleDbCommand command, object[] commandParameters)
        {
            foreach (object obj2 in commandParameters)
            {
                OleDbParameter parameter = (OleDbParameter)obj2;
                if ((parameter.Direction == ParameterDirection.InputOutput) && (parameter.Value == null))
                {
                    parameter.Value = DBNull.Value;
                }
                command.Parameters.Add(parameter);
            }
        }

        #region 接口实现

        /// <summary>
        /// 关闭数据库连接
        /// </summary>
        public void Close()
        {
        }

        /// <summary>
        ///提交事务
        /// </summary>
        /// <param name="oDBTransaction"></param>
        public void Commit(object oDBTransaction)
        {
            OleDbTransaction transaction = (OleDbTransaction)oDBTransaction;
            OleDbConnection connection = transaction.Connection;
            try
            {
                try
                {
                    transaction.Commit();
                }
                catch (Exception exception)
                {
                    transaction.Rollback();
                    this.errorMessage = exception.ToString();
                    throw new ApplicationException("提交事务失败：" + exception.Message);//提交事务失败
                }
            }
            finally
            {
                transaction.Dispose();
                transaction = null;
                connection.Close();
            }
        }

        /// <summary>
        /// 创建参数
        /// </summary>
        /// <param name="strName"></param>
        /// <param name="strValue"></param>
        /// <param name="pdType"></param>
        /// <param name="iSize"></param>
        /// <returns></returns>
        public object CreateParameter(string strName, object strValue, ParameterDirection pdType, int iSize)
        {
            OleDbParameter parameter = new OleDbParameter(strName, strValue);
            if (strValue.ToString().Length > 0xbb8)
            {
                parameter.OleDbType = OleDbType.LongVarChar;
            }
            else
            {
                parameter.OleDbType = OleDbType.VarChar;
            }
            parameter.Direction = pdType;
            parameter.Size = iSize;
            return parameter;
        }

        /// <summary>
        /// 创建事务
        /// </summary>
        /// <returns></returns>
        public object CreateTransaction()
        {
            OleDbConnection connection = new OleDbConnection();
            connection.ConnectionString = this.connectionString;
            connection.Open();
            return connection.BeginTransaction();
        }

        /// <summary>
        /// 事务执行语句
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="oDBTransaction"></param>
        public void Execute(string strSql, object oDBTransaction)
        {
            OleDbTransaction transaction = (OleDbTransaction)oDBTransaction;
            OleDbConnection connection = transaction.Connection;
            if (transaction.Connection == null)
            {
                connection = new OleDbConnection();
            }
            OleDbCommand command = new OleDbCommand();
            command.CommandTimeout = DB.CommandTimeout;
            this.PrepareCommand(command, connection, true, ref transaction, CommandType.Text, strSql, null);
            try
            {
                command.ExecuteNonQuery();
            }
            catch (Exception exception)
            {
                transaction.Rollback();
                transaction.Dispose();
                transaction = null;
                connection.Close();
                this.errorMessage = exception.ToString() + ":" + strSql;
                throw new ApplicationException("指令执行失败：" + this.errorMessage);//指令执行失败
            }
        }

        /// <summary>
        /// 数据库操作
        /// </summary>
        /// <param name="SQL"></param>
        /// <param name="IsNeedTransaction"></param>
        /// <param name="transaction"></param>
        /// <param name="commandType"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public bool Execute(string SQL, bool IsNeedTransaction, object transaction, CommandType commandType, params object[] parameters)
        {
            bool flag;
            if (transaction != null)
            {
                IsNeedTransaction = true;
            }
            if ((SQL == null) || (SQL == ""))
            {
                this.errorMessage = "SQL语句为空";
                return false;
            }
            OleDbConnection connection = new OleDbConnection();
            OleDbCommand command = new OleDbCommand();
            command.CommandTimeout = DB.CommandTimeout;
            OleDbTransaction transaction2 = null;
            try
            {
                transaction2 = (OleDbTransaction)transaction;
                this.PrepareCommand(command, connection, IsNeedTransaction, ref transaction2, commandType, SQL, parameters);
                command.ExecuteNonQuery();
                if (IsNeedTransaction && (transaction == null))
                {
                    transaction2.Commit();
                }
                flag = true;
            }
            catch (Exception exception)
            {
                this.errorMessage = exception.ToString();
                if (IsNeedTransaction && (transaction == null))
                {
                    try
                    {
                        transaction2.Rollback();
                    }
                    catch
                    {
                    }
                }
                throw exception;
            }
            finally
            {
                connection.Close();
            }
            return flag;
        }

        /// <summary>
        /// 执行数据库存储过程
        /// </summary>
        /// <param name="strProcedureName"></param>
        /// <param name="oParameters"></param>
        public void ExecuteProcedure(string strProcedureName, object[] oParameters)
        {
            OleDbConnection connection = new OleDbConnection(this.connectionString);
            try
            {
                try
                {
                    connection.Open();
                    OleDbCommand command = new OleDbCommand();
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = strProcedureName;
                    foreach (object obj2 in oParameters)
                    {
                        command.Parameters.Add((OleDbParameter)obj2);
                    }
                    command.Connection = connection;
                    command.ExecuteNonQuery();
                }
                catch (Exception exception)
                {
                    this.errorMessage = exception.ToString() + ":" + strProcedureName;
                    throw new ApplicationException("指令执行失败：" + this.errorMessage);//指令执行失败
                }
            }
            finally
            {
                connection.Close();
            }
        }

        /// <summary>
        /// 获取DataReader
        /// </summary>
        /// <param name="SQL"></param>
        /// <param name="IsNeedTransaction"></param>
        /// <param name="transaction"></param>
        /// <param name="commandType"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public DataReader GetDataReader(string SQL, bool IsNeedTransaction, object transaction, CommandType commandType, params object[] parameters)
        {
            DataReader reader2;
            this.errorMessage = "";
            if ((SQL == null) || (SQL.Trim() == ""))
            {
                return null;
            }
            OleDbConnection connection = new OleDbConnection();
            OleDbTransaction transaction2 = null;
            OleDbCommand command = null;
            try
            {
                transaction2 = (OleDbTransaction)transaction;
                command = new OleDbCommand();
                command.CommandTimeout = DB.CommandTimeout;
                this.PrepareCommand(command, connection, IsNeedTransaction, ref transaction2, commandType, SQL, parameters);
                OleDbDataReader reader = command.ExecuteReader();
                if (IsNeedTransaction && (transaction == null))
                {
                    transaction2.Commit();
                }
                reader2 = new DataReader(reader, connection);
            }
            catch (Exception exception)
            {
                this.errorMessage = exception.ToString();
                if (IsNeedTransaction && (transaction == null))
                {
                    transaction2.Rollback();
                }
                throw exception;
            }
            finally
            {
                connection.Close();
            }
            return reader2;
        }

        /// <summary>
        /// 获取DataSet
        /// </summary>
        /// <param name="SQL"></param>
        /// <param name="Alias"></param>
        /// <param name="IsNeedTransaction"></param>
        /// <param name="transaction"></param>
        /// <param name="commandType"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public DataSet GetDataSet(string SQL, string Alias, bool IsNeedTransaction, object transaction, CommandType commandType, params object[] parameters)
        {
            DataSet set2;
            if ((SQL == null) || (SQL == ""))
            {
                return null;
            }
            OleDbConnection connection = new OleDbConnection();
            OleDbTransaction transaction2 = null;
            OleDbCommand command = null;
            try
            {
                transaction2 = (OleDbTransaction)transaction;
                OleDbDataAdapter adapter = new OleDbDataAdapter();
                command = new OleDbCommand();
                command.CommandTimeout = DB.CommandTimeout;
                this.PrepareCommand(command, connection, IsNeedTransaction, ref transaction2, commandType, SQL, parameters);
                adapter.SelectCommand = command;
                if ((parameters != null) && (parameters.Length != 0))
                {
                    this.AttachParameters(adapter.SelectCommand, parameters);
                }
                DataSet dataSet = new DataSet();
                if ((Alias == null) || (Alias == ""))
                {
                    Alias = "Alias";
                }
                adapter.Fill(dataSet, Alias);
                if (IsNeedTransaction && (transaction == null))
                {
                    transaction2.Commit();
                }
                set2 = dataSet;
            }
            catch (Exception exception)
            {
                this.errorMessage = exception.ToString();
                if (IsNeedTransaction && (transaction == null))
                {
                    try
                    {
                        transaction2.Rollback();
                    }
                    catch
                    {
                    }
                }
                throw exception;
            }
            finally
            {
                connection.Close();
            }
            return set2;
        }

        /// <summary>
        /// 获取DataView
        /// </summary>
        /// <param name="SQL"></param>
        /// <param name="IsNeedTransaction"></param>
        /// <param name="transaction"></param>
        /// <param name="commandType"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public DataView GetDataView(string SQL, bool IsNeedTransaction, object transaction, CommandType commandType, params object[] parameters)
        {
            DataSet set = new DataSet();
            set = this.GetDataSet(SQL, "Alias", IsNeedTransaction, transaction, commandType, parameters);
            if (set == null)
            {
                return null;
            }
            return set.Tables["Alias"].DefaultView;
        }

        /// <summary>
        /// 获取指定列值
        /// </summary>
        /// <param name="SQL"></param>
        /// <param name="FieldName"></param>
        /// <param name="IsNeedTransaction"></param>
        /// <param name="transaction"></param>
        /// <param name="commandType"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public string GetFieldValue(string SQL, string FieldName, bool IsNeedTransaction, object transaction, CommandType commandType, params object[] parameters)
        {
            DataView view = this.GetDataView(SQL, IsNeedTransaction, transaction, commandType, parameters);
            if ((view != null) && (view.Table.Rows.Count > 0))
            {
                if ((FieldName != null) && (FieldName != ""))
                {
                    try
                    {
                        return view.Table.Rows[0][FieldName].ToString();
                    }
                    catch
                    {
                        return view.Table.Rows[0][0].ToString();
                    }
                }
                return view.Table.Rows[0][0].ToString();
            }
            return null;
        }

        /// <summary>
        /// 获取参数
        /// </summary>
        /// <param name="oParameter"></param>
        /// <returns></returns>
        public object GetParameterValue(object oParameter)
        {
            OleDbParameter parameter = (OleDbParameter)oParameter;
            return parameter.Value;
        }

        private void PrepareCommand(OleDbCommand command, OleDbConnection connection, bool IsNeedTransaction, ref OleDbTransaction transaction, CommandType commandType, string commandText, params object[] commandParameters)
        {
            if (transaction == null)
            {
                if (connection.State != ConnectionState.Open)
                {
                    connection.ConnectionString = this.connectionString;
                    connection.Open();
                }
            }
            else
            {
                connection = transaction.Connection;
                if (connection.State != ConnectionState.Open)
                {
                    connection.Open();
                }
            }
            if (command == null)
            {
                command = new OleDbCommand();
            }
            command.Connection = connection;
            command.CommandText = commandText;
            if (IsNeedTransaction)
            {
                if (transaction != null)
                {
                    command.Transaction = transaction;
                }
                else
                {
                    transaction = connection.BeginTransaction();
                    command.Transaction = transaction;
                }
            }
            command.CommandType = commandType;
            if ((commandParameters != null) && (commandParameters.Length != 0))
            {
                this.AttachParameters(command, commandParameters);
            }
        }


        /// <summary>
        /// 回滚事务
        /// </summary>
        /// <param name="oDBTransaction"></param>
        public void RollBack(object oDBTransaction)
        {
            OleDbTransaction transaction = (OleDbTransaction)oDBTransaction;
            try
            {
                transaction.Rollback();
            }
            catch
            {
            }
        }

        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public string Connection
        {
            get
            {
                return this.connectionString;
            }
            set
            {
                this.connectionString = value;
            }
        }

        /// <summary>
        /// 数据库连接类型
        /// </summary>
        public ConnectionType ConnType
        {
            get
            {
                return this.connType;
            }
            set
            {
                this.connType = value;
            }
        }

        /// <summary>
        /// 错误信息
        /// </summary>
        public string ErrMessage
        {
            get
            {
                return this.errorMessage;
            }
        }

        #endregion
    }
}

